import java.util.*;

/**
 * @author LKQ
 * @date 2022/4/18 17:41
 * @description 本题考察主要内容，Dijkstra算法，以及抽象化建图能力
 */
public class Example {
    /**
     * 服务器名称 - 编号
     */
    public static Map<String, Integer> map = new HashMap<>();
    /**
     * 邻接表存储 连通关系
     */
    public static List<int[]>[] graph;

    public static Scanner sc;

    final static long INF = Long.MAX_VALUE / 2;

    public static void main(String[] args) {
        sc = new Scanner(System.in);
        String[] firstLine = sc.nextLine().split(" ");
        // 服务器数量n 和 数据线数量 m
        int n = Integer.parseInt(firstLine[0]), m = Integer.parseInt(firstLine[1]);
        buildGraph(n, m);
        int query = Integer.parseInt(sc.nextLine());
        for (int i = 0; i < query; i++) {
            String[] data = sc.nextLine().split(" ");
            int src = map.get(data[0]), target = map.get(data[1]);
            long result = dijkstra(src, target, graph);
            if (result == INF) {
                System.out.println("INF");
            } else {
                System.out.println(result);
            }
        }
    }
    public static void buildGraph(int n, int m) {
        // 建图，服务器名称和编号对应
        map = new HashMap<>();
        // 两台服务器连接邻接表
        graph = new List[n];
        for (int i = 0; i < n; i++) {
            graph[i] = new ArrayList<>();
        }
        for (int i = 0, j = 0; i < m; i++) {
            String[] data = sc.nextLine().split(" ");
            String from = data[0], to = data[1];
            int time = Integer.parseInt(data[2]);
            if (!map.containsKey(from)) {
                map.put(from, j++);
            }
            if (!map.containsKey(to)) {
                map.put(to, j++);
            }
            int f = map.get(from), t = map.get(to);
            graph[f].add(new int[]{t, time});
        }
    }
    public static long dijkstra(int src, int target, List<int[]>[] graph) {
        int n = graph.length;
        PriorityQueue<long[]> pq = new PriorityQueue<>((o1, o2) -> Long.compare(o1[1], o2[1]));
        // 开始服务器，耗时
        pq.offer(new long[]{src, 0});
        long[] dest = new long[n];
        Arrays.fill(dest, INF);
        dest[src] = 0;
        boolean[] vis = new boolean[n];
        while (!pq.isEmpty()) {
            long[] cur = pq.poll();
            long uu = cur[0], t = cur[1];
            int u = (int)uu;
            if (u == target) {
                break;
            }
            if (vis[u]) {
                continue;
            }
            vis[u] = true;
            for (int[] next : graph[u]) {
                int v = next[0], cost = next[1];
                if (t + cost < dest[v]) {
                    dest[v] = t + cost;
                    pq.offer(new long[]{v, t + cost});
                }
            }
        }
        return dest[target];
    }
}
